package app.project.streetlensproject.util;

import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Nhung function co ban nhat. hau het app nao cung su dung no 
 * @author Quan
 *
 */
public class CommonUtils {

	/*
	 * Check SD card
	 */

	public static boolean checkSDCard() {
		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		return mExternalStorageAvailable & mExternalStorageWriteable;
	}

	/**
	 * Kiem tra xem co google play hay khong
	 */
	public static boolean checkHasGooglePlay(Context context) {
		Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.rubycell.pianisthd"));
		if (i.resolveActivity(context.getPackageManager()) != null)
			return true;
		return false;
	}
	
	/**
	 * Open google play voi tham so truyen vao la appID (package name) tuong ung
	 */
	public static void openAppFromMarket(Activity activity, String appID) {
		try {
			try {
				activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appID)));
			} catch (android.content.ActivityNotFoundException anfe) {
				activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse("http://play.google.com/store/apps/details?id=" + appID)));
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	public static boolean isOnline(Context mContext) {
		ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	/**
	 * get device ID. neu khong lay duoc se tra ve la sau rong
	 * 
	 */
	public static String getDeviceId(Context mContext) {
		try {
			TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
			String id = telephonyManager.getDeviceId();
			return id;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static void saveBooleanSetting(Context mContext, String pKey, boolean pValue) {
		Editor mEditor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
		mEditor.putBoolean(pKey, pValue);
		mEditor.commit();
	}

	public static boolean getBooleanSetting(Context mContext, String pKey, boolean mDefaultValue) {
		SharedPreferences mSharePreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
		boolean mValue = mSharePreferences.getBoolean(pKey, mDefaultValue);
		return mValue;
	}
	
	public static void saveFloatSetting(Context mContext, String pKey, float pValue) {
		Editor mEditor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
		mEditor.putFloat(pKey, pValue);
		mEditor.commit();
	}

	public static float getFloatSetting(Context mContext, String pKey, float mDefaultValue) {
		SharedPreferences mSharePreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
		float mValue = mSharePreferences.getFloat(pKey, mDefaultValue);
		return mValue;
	}

	public static void saveStringSetting(Context mContext, String pKey, String pValue) {
		Editor mEditor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
		mEditor.putString(pKey, pValue);
		mEditor.commit();
	}

	public static String getStringSetting(Context mContext, String pKey, String mDefaultValue) {
		SharedPreferences mSharePreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
		String mValue = mSharePreferences.getString(pKey, mDefaultValue);
		return mValue;
	}

	public static void saveLongSetting(Context mContext, String pKey, long pValue) {
		Editor mEditor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
		mEditor.putLong(pKey, pValue);
		mEditor.commit();
	}

	public static Long getLongSetting(Context mContext, String pKey, long mDefaultValue) {
		if (mContext == null)
			return mDefaultValue;
		SharedPreferences mSharePreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
		long mValue = mSharePreferences.getLong(pKey, mDefaultValue);
		return mValue;
	}

	public static void saveIntSetting(Context mContext, String pKey, int pValue) {
		Editor mEditor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
		mEditor.putInt(pKey, pValue);
		mEditor.commit();
	}

	public static int getIntSetting(Context mContext, String pKey, int mDefaultValue) {
		if (mContext == null)
			return mDefaultValue;
		SharedPreferences mSharePreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
		int mValue = mSharePreferences.getInt(pKey, mDefaultValue);
		return mValue;
	}

	public static void changeLanguage(Context context, int languageIndex, String[] lo) {
		String lang = "en";
		try {
			lang = lo[languageIndex];
			Log.d("Utility", "+++++++++++++++current language=" + lang);
			Configuration configuration = context.getResources().getConfiguration();

			if (!"".equals(lang) && !configuration.locale.getLanguage().equals(lang)) {
				Locale locale = new Locale(lang);
				Locale.setDefault(locale);
				configuration.locale = locale;
				context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static boolean isTablet(Context context) {
		boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
		boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
		return (xlarge || large);
	}

	public static int getScreenLayoutSize(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK);
	}

	public static float convertDpToPixel(Context context, float dp) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float px = dp * (metrics.densityDpi / 160f);
		return px;
	}

	public static boolean hasFroyo() {
        // Can use static final constants like FROYO, declared in later versions
        // of the OS since they are inlined at compile time. This is guaranteed behavior.
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    public static boolean hasGingerbread() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
    }

    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
    }

//    public static boolean hasJellyBean() {
//        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
//    }

    public static void hideSoftKey(Context context, EditText edt){
    	InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        Intent mIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        if (mIntent != null) {
            return true;
        }
        else {
            return false;
        }
    }
}
